<?php
use Symfony\Component\Process\Process;
use \Buzz\Browser;
use \Istat;

require __DIR__.'/bootstrap.php';
$browser = new Browser();


$params = getopt( 'igd:u::', array('import', 'geo', 'dataset:', 'url::'));

$do_import = false;
if (isset($params['i']) || isset($params['import'])) $do_import = true;

$dataset = '';
if (isset($params['d']) || isset($params['dataset'])) $dataset = $params['d'];

$use_geolocal = false;
if (isset($params['g']) || isset($params['geo'])) $use_geolocal = true;


echo "Elaboro $dataset\n";

switch ($dataset) {
	case 'pm10':
		$istat = new Istat\Pm10($browser); 
		break;
        case 'verde': 
		$istat = new Istat\Verde($browser); 
		break;
	case 'acustico':
		$istat = new Istat\Acustico($browser);
		break;
        case 'trasporto':
              $istat = new Istat\Trasporto($browser);
              break;
	default: 
		echo "Nessun dataset selezionato\n";
		echo "Puoi selezionare:\n";
		echo "pm10, verde, acustico, trasporto\n";
		die();
}

$istat->importCities(__DIR__.'/cities.txt');

if ($do_import)
{
  $file = $istat->savePath(__DIR__.'/urls', '.url');
  fwrite( $file, implode("\n",$istat->generateUrls()));
  fclose($file);

  /** STEP 2 - CREO LA LISTA DELLE URL */

  if (!is_dir(dirname(__FILE__).'/urls/'.$istat->getDataSet()))
  {
    echo "creo directory e parso file\n";
    $process = new Process(' mkdir '.__DIR__.'/urls/'.$istat->getDataSet().' && cd '.__DIR__.'/urls/'.$istat->getDataSet().' && wget -i '.__DIR__.'/urls/'.$istat->getDataSet().'.url.txt');
    $process->run(function ($type, $buffer) {
        echo 'OUT > '.$buffer;
    });
  }
}

  /** STEP 3 - parso i file e salvo su db e file **/

  $dir = dirname(__FILE__).'/urls/'.$istat->getDataSet();
  $files = array();

  $content = new DirectoryIterator($dir); 
  foreach ($content as $file)
  {
	if ($file->isFile()) 
	{
		$data = file_get_contents($dir.'/'.$file->getFilename());
		$c = json_decode($data);

		if ($use_geolocal) sleep(5);

		echo 'leggo: '.$file->getFilename()." - ";
		if ($c) {
                        $place = $istat->parsePlace($c, $use_geolocal);    
			$files[] = $place;
//			$connection->insert(json_encode($place));
		}
		else {
			echo 'FILE VUOTO!';
		}
		echo "\n";
	}
  }

$t_min = $t_max = array(); $max = 0; $min = 9999;
foreach ($files as $f) {
  foreach ($f->value as $k => $v) {
    if (!isset($t_min[$k])) { $t_min[$k] = 0; }
    if (!isset($t_max[$k])) { $t_max[$k] = 0; }

    if ($t_max[$k] < $v) { $t_max[$k] = $v; }
    if ($t_min[$k] > $v) { $t_min[$k] = $v; }

  }
}


$mongo = new Mongo();
$connection = $mongo->silex->territorio;

foreach ($files as $f) {
  foreach ($f->value as $k => $v) {
    $f->normalized_score[$k] = round($v * 4 / $t_max[$k]);
  }

  $connection->insert(get_object_vars($f));
//  print_r($f->normalized_score);
}

$file = $istat->savePath(__DIR__.'/urls', '.data');
fwrite($file, json_encode($files));
fclose($file);

//print_r($t_max);
//print_r($t_min);


